<template>
  <div class="rescue-info-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Warning /></el-icon>
            <span class="header-title">救助信息管理</span>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="search.animalType"
          placeholder="搜索动物类型"
          clearable
          style="max-width: 200px;"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select 
          v-model="search.status" 
          placeholder="选择状态" 
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="0" />
          <el-option label="进行中" :value="1" />
          <el-option label="已完成" :value="2" />
          <el-option label="驳回" :value="3" />
        </el-select>
        <el-button type="primary" @click="handleSearch" :icon="Search">查询</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="rescueCode" label="救助编号" width="180" align="center">
          <template #default="{ row }">
            <span class="code-text">{{ row.rescueCode || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="animalType" label="动物类型" width="120" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="small">{{ row.animalType || '-' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span :title="row.description">{{ row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="发现地点" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <div class="location-cell">
              <el-icon><Location /></el-icon>
              <span>{{ row.location || '-' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="photo" label="现场照片" width="150" align="center">
          <template #default="{ row }">
            <div 
              v-if="getPhotoList(row.photo).length > 0"
              class="image-preview-cell"
              @click="previewRescueImage(row)"
            >
              <el-image
                :src="getPhotoList(row.photo)[0]"
                fit="cover"
                style="width: 65px; height: 65px; border-radius: 8px; cursor: pointer; border: 2px solid #e4e7ed;"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <span v-if="getPhotoList(row.photo).length > 1" class="photo-count">
                {{ getPhotoList(row.photo).length }}
              </span>
            </div>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="reporterId" label="上报人ID" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.reporterId || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="reportTime" label="上报时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.reportTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="rejectReason" label="驳回原因" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.rejectReason" :title="row.rejectReason" class="reject-reason">
              {{ row.rejectReason }}
            </span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="row.status === 0"
              size="small" 
              type="success" 
              @click="approve(row)"
              :icon="Check"
              :loading="approving === row.id"
            >
              通过
            </el-button>
            <el-button 
              v-if="row.status === 0"
              size="small" 
              type="warning" 
              @click="reject(row)"
              :icon="Close"
            >
              驳回
            </el-button>
            <span v-else style="color: #909399;">已处理</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && tableData.length === 0" 
        description="暂无救助信息"
        style="margin: 40px 0;"
      />

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 驳回弹窗 -->
    <el-dialog 
      v-model="rejectDialog.visible" 
      title="驳回原因" 
      width="600px"
      @close="handleRejectDialogClose"
    >
      <el-form>
        <el-form-item label="驳回原因" required>
          <el-input 
            type="textarea" 
            v-model="rejectDialog.reason" 
            placeholder="请输入驳回原因"
            :rows="5"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="rejectDialog.visible = false">取消</el-button>
          <el-button type="warning" @click="submitReject" :loading="rejecting">确定驳回</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 - 完全按照 RescueManage.vue 的方式 -->
    <el-dialog 
      v-model="imagePreviewVisible" 
      title="图片预览" 
      width="90%"
      class="preview-dialog"
      @closed="handleImagePreviewClosed"
    >
      <div class="preview-container">
        <!-- 工具栏 -->
        <div class="preview-toolbar">
          <div class="toolbar-left">
            <el-button-group>
              <el-button @click="zoomOut" :icon="ZoomOut" :disabled="zoomScale <= 0.5" title="缩小">
                缩小
              </el-button>
              <el-button @click="resetZoom" title="重置">
                {{ Math.round(zoomScale * 100) }}%
              </el-button>
              <el-button @click="zoomIn" :icon="ZoomIn" :disabled="zoomScale >= 3" title="放大">
                放大
              </el-button>
            </el-button-group>
          </div>
          <div class="toolbar-right">
            <span class="preview-counter">
              共 {{ previewImageList.length }} 张图片，当前第 {{ previewImageIndex + 1 }} 张
            </span>
          </div>
        </div>
        
        <!-- 轮播容器 -->
        <div class="carousel-wrapper">
          <el-carousel 
            v-model="previewImageIndex"
            height="70vh"
            indicator-position="outside"
            @change="handleCarouselChange"
          >
            <el-carousel-item v-for="(url, index) in previewImageList" :key="index">
              <div class="carousel-image-wrapper" @wheel.prevent="handleWheel">
                <div 
                  class="image-zoom-container"
                  :style="{ transform: `scale(${zoomScale})` }"
                >
                  <img 
                    :src="url" 
                    class="preview-image"
                    alt="预览图片"
                    @load="handleImageLoad"
                    @error="handleImageError"
                  />
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Warning, Search, Refresh, Close, Location, Picture, Check, ZoomIn, ZoomOut } from '@element-plus/icons-vue'
import axios from 'axios'

const tableData = ref([])
const page = ref(1)
const size = ref(10)
const total = ref(0)
const loading = ref(false)
const rejecting = ref(false)
const approving = ref(null)
const search = ref({ animalType: '', status: null })

const rejectDialog = ref({ visible: false, id: null, reason: '' })

// 图片预览相关 - 完全按照 RescueManage.vue 的方式
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')
const previewImageList = ref([])
const previewImageIndex = ref(0)
const zoomScale = ref(1) // 图片缩放比例

const formatTime = (time) => {
  if (!time) return '-'
  if (typeof time === 'string' && time.includes('T')) {
    return time.replace('T', ' ').substring(0, 19)
  }
  return time
}

const getPhotoList = (photo) => {
  if (!photo) return []
  if (typeof photo === 'string') {
    return photo.split(',').filter(url => url.trim() !== '')
  }
  return Array.isArray(photo) ? photo : []
}

// 预览救助图片
const previewRescueImage = (row) => {
  const photoList = getPhotoList(row.photo)
  if (photoList.length > 0) {
    previewImageList.value = photoList.map(url => url.trim())
    previewImageUrl.value = photoList[0].trim()
    previewImageIndex.value = 0
    zoomScale.value = 1 // 重置缩放
    imagePreviewVisible.value = true
  } else {
    ElMessage.warning('该记录没有图片')
  }
}

// 图片缩放相关方法
const zoomIn = () => {
  if (zoomScale.value < 3) {
    zoomScale.value = Math.min(zoomScale.value + 0.25, 3)
  }
}

const zoomOut = () => {
  if (zoomScale.value > 0.5) {
    zoomScale.value = Math.max(zoomScale.value - 0.25, 0.5)
  }
}

const resetZoom = () => {
  zoomScale.value = 1
}

// 鼠标滚轮缩放
const handleWheel = (event) => {
  event.preventDefault()
  if (event.deltaY < 0) {
    // 向上滚动，放大
    zoomIn()
  } else {
    // 向下滚动，缩小
    zoomOut()
  }
}

// 轮播切换
const handleCarouselChange = () => {
  // 切换图片时保持当前缩放比例
}

// 关闭图片预览
const handleImagePreviewClosed = () => {
  previewImageUrl.value = ''
  previewImageList.value = []
  previewImageIndex.value = 0
  zoomScale.value = 1
}

// 图片加载完成处理
const handleImageLoad = (event) => {
  // 确保图片完整显示，不裁剪
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  ElMessage.error('图片加载失败')
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待审核',
    1: '进行中',
    2: '已完成',
    3: '驳回'
  }
  return statusMap[status] || '未知'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

async function loadData() {
  loading.value = true
  try {
    const params = {
      page: page.value,
      size: size.value
    }
    if (search.value.animalType) {
      params.animalType = search.value.animalType
    }
    if (search.value.status !== null && search.value.status !== '') {
      params.status = search.value.status
    }
    
    const res = await axios.get('http://localhost:8080/api/admin/rescue/list', { params })
    if (res.data.code === 200) {
      tableData.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.data.msg || '获取数据失败')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取救助信息失败:', error)
    ElMessage.error('获取数据失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

async function approve(row) {
  try {
    await ElMessageBox.confirm(
      `确定要通过编号"${row.rescueCode}"的救助申请吗？`,
      '审核确认',
      {
        confirmButtonText: '确定通过',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    approving.value = row.id
    const res = await axios.post('http://localhost:8080/api/admin/rescue/approve', null, {
      params: { id: row.id }
    })
    
    if (res.data.code === 200) {
      ElMessage.success('审核通过')
      loadData()
    } else {
      ElMessage.error(res.data.msg || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error(error.response?.data?.msg || '审核失败')
    }
  } finally {
    approving.value = null
  }
}

function reject(row) {
  rejectDialog.value = { visible: true, id: row.id, reason: '' }
}

const handleRejectDialogClose = () => {
  rejectDialog.value = { visible: false, id: null, reason: '' }
}

async function submitReject() {
  if (!rejectDialog.value.reason || rejectDialog.value.reason.trim() === '') {
    ElMessage.warning('请输入驳回原因')
    return
  }
  
  rejecting.value = true
  try {
    const res = await axios.post('http://localhost:8080/api/admin/rescue/reject', null, {
      params: { 
        id: rejectDialog.value.id, 
        reason: rejectDialog.value.reason.trim() 
      }
    })
    if (res.data.code === 200) {
      ElMessage.success('已驳回')
      rejectDialog.value.visible = false
      loadData()
    } else {
      ElMessage.error(res.data.msg || '驳回失败')
    }
  } catch (error) {
    console.error('驳回失败:', error)
    ElMessage.error('驳回失败：' + (error.response?.data?.msg || error.message || '未知错误'))
  } finally {
    rejecting.value = false
  }
}

const handleSearch = () => {
  page.value = 1
  loadData()
}

const handleReset = () => {
  search.value = { animalType: '', status: null }
  page.value = 1
  loadData()
}

const handleSizeChange = (newSize) => {
  size.value = newSize
  page.value = 1
  loadData()
}

const handleCurrentChange = (newPage) => {
  page.value = newPage
  loadData()
}

onMounted(loadData)
</script>

<style scoped>
.rescue-info-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #E6A23C;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #409eff;
}

.location-cell {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
}

.location-cell .el-icon {
  color: #909399;
  font-size: 16px;
}

.image-preview-cell {
  display: inline-block;
  position: relative;
  cursor: pointer;
}

.image-preview-cell:hover {
  opacity: 0.8;
}

.photo-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  font-weight: 600;
  line-height: 1.2;
  min-width: 20px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.reject-reason {
  color: #f56c6c;
  font-size: 13px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: #f5f7fa;
}

:deep(.el-table__header th) {
  background: #f5f7fa !important;
  border-bottom: 2px solid #e4e7ed;
  padding: 16px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__body td) {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 操作按钮组样式 */
:deep(.el-table__body .cell) {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

<!-- 预览对话框样式 - 完全按照 RescueManage.vue 的方式 -->
<style>
.preview-container {
  background: #1a1a1a;
  border-radius: 8px;
  overflow: hidden;
  padding: 20px;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 6px;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  align-items: center;
}

.preview-counter {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.carousel-wrapper {
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.carousel-image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 70vh;
  overflow: auto;
  background: #000;
}

.image-zoom-container {
  display: inline-block;
  transition: transform 0.3s ease;
  transform-origin: center center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
  display: block;
  user-select: none;
}

:deep(.preview-dialog .el-dialog) {
  margin: 5vh auto !important;
}

:deep(.preview-dialog .el-dialog__body) {
  padding: 20px !important;
  background: #1a1a1a;
}

:deep(.el-carousel__container) {
  height: 70vh !important;
}

:deep(.el-carousel__item) {
  height: 70vh !important;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(255, 255, 255, 0.3);
  border: none;
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(255, 255, 255, 0.5);
}

:deep(.el-carousel__indicators) {
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 20px;
  padding: 8px;
}
</style>